using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	/// <summary>
	/// 更新挂号单模板命令处理器
	/// </summary>
	public class UpdateRegistrationSlipTemplateCommandHandler : IRequestHandler<UpdateRegistrationSlipTemplateCommand, RegistrationSlipTemplateDto>
	{
		private readonly IBaseRepository<RegistrationSlipTemplate> _repository;

		public UpdateRegistrationSlipTemplateCommandHandler(IBaseRepository<RegistrationSlipTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<RegistrationSlipTemplateDto> Handle(UpdateRegistrationSlipTemplateCommand request, CancellationToken cancellationToken)
		{
			var entity = await _repository.GetModel(x => x.TemplateId == request.TemplateId && !x.IsDeleted);
			
			if (entity == null)
			{
				throw new Exception("模板不存在");
			}

			// 更新字段（仅更新提供的字段）
			if (!string.IsNullOrEmpty(request.TemplateName))
			{
				entity.TemplateName = request.TemplateName;
			}

			if (request.Description != null)
			{
				entity.Description = request.Description;
			}

			if (request.IsActive.HasValue)
			{
				entity.IsActive = request.IsActive.Value;
			}

			if (request.IsDefault.HasValue)
			{
				entity.IsDefault = request.IsDefault.Value;
			}

			if (request.PriorityRules != null)
			{
				entity.PriorityRules = request.PriorityRules;
			}

			if (request.ConfiguredFields != null)
			{
				entity.ConfiguredFields = request.ConfiguredFields;
			}

			entity.UpdatedAt = DateTime.Now;

			await _repository.UpdateAsync(entity);

			return new RegistrationSlipTemplateDto
			{
				TemplateId = entity.TemplateId,
				TemplateName = entity.TemplateName,
				Description = entity.Description,
				IsActive = entity.IsActive,
				IsDefault = entity.IsDefault,
				PriorityRules = entity.PriorityRules,
				ConfiguredFields = entity.ConfiguredFields,
				CreatedAt = entity.CreatedAt,
				UpdatedAt = entity.UpdatedAt
			};
		}
	}
}
